package ee.example.final_work

import android.app.FragmentManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.final_work.R

class New1 : AppCompatActivity() {
    private var txt_title: TextView? = null
    private var fl_content: FrameLayout? = null
    private var mContext: Context? = null
    private var datas: ArrayList<NewsBean>? = null
    private var fManager: FragmentManager? = null
    private var exitTime: Long = 0
    var mSQLiteHelper: SQLiteHelper? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        mContext = this@New1
        fManager = fragmentManager
        bindViews()
        initData()
    }

    private fun initData() {
        datas = ArrayList()
        mSQLiteHelper = SQLiteHelper(this) //创建数据库
        if (datas != null) {
            datas!!.clear()
        }
        //从数据库中查询数据(保存的标签)
        datas = mSQLiteHelper!!.query()
        val nlFragment = NewListFragment(fManager!!, datas!!)
        val ft = fManager!!.beginTransaction()
        ft.replace(R.id.fl_content, nlFragment)
        ft.commit()
    }

    private fun bindViews() {
        txt_title = findViewById<View>(R.id.txt_title) as TextView
        fl_content = findViewById<View>(R.id.fl_content) as FrameLayout
        val add = findViewById<View>(R.id.add) as ImageView
        if (Data.sta_np == true) {
            if (Data.sta_name == "admin") {
                add.visibility = View.VISIBLE
            }
        }
        //设置点击事件
        add.setOnClickListener { //页面跳转
            val intent = Intent(
                this@New1,
                AddActivity::class.java
            )
            startActivityForResult(intent, 1)
        }
    }

    //点击回退键的处理：判断Fragment栈中是否有Fragment
    //没，双击退出程序，否则像是Toast提示
    //有，popbackstack弹出栈
    override fun onBackPressed() {
        if (fManager!!.backStackEntryCount == 0) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(
                    applicationContext, "再按一次退出程序",
                    Toast.LENGTH_SHORT
                ).show()
                exitTime = System.currentTimeMillis()
            } else {
                super.onBackPressed()
            }
        } else {
            fManager!!.popBackStack()
            txt_title!!.text = "新闻列表"
        }
    }

    //页面回调监听刷新事件
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == 2) {
            initData()
        }
    }
}